import {action, observable} from 'mobx';
import objectAssign from 'object-assign';
import {message} from 'antd';
import {WeaTools,WeaLocaleProvider} from 'ecCom';
import * as API_ADD from '../apis/add';

const {ls} = WeaTools;
const getLabel = WeaLocaleProvider.getLabel;
const Base64 = WeaTools.Base64;


export class WFAddStore {
	
	wftypes = [];
	createwflabels = {};
	tabDatas = [];
	unSupportSPAWf = [];
	wfTypeTips = {};//流程创建页面，流程类型后面显示的WeaHelpfulTip提示信息
	title;
	initParams = {};

//	@observable	typesShow = [];
//	@observable	typesCols = [];
//	@observable	usedBeans = [];
//	@observable	abcBtns = [];
//	@observable	commonuse = '';
//	@observable user = {};
	
	@observable showDatas = {
		typesShow : [],
		typesCols : [],
		usedBeans : [],
		abcBtns : [],
		commonuse :'',
		user : ''
	}
	
	@observable	value = "";
	@observable	tabkey = ls.getStr('wf-add-tabkey') || '1';
	@observable	mulitcol = ls.getStr('wf-add-mulitcol') == 'false' ? false : true; //true:four false:one
	@observable	isAbc = ls.getStr('wf-add-isAbc') == 'true' ? true : false;
	@observable	abcSelected = "";
	@observable	loading = false;
	
	importData =  [];
	importValue = "";
	@observable	importDataShow =  [];
	
	@observable wfOperateInfo = {
		curOperWfid:0,
		showBeagenters:false,
		showImportWf:false,
        isDisableImportWfMenu:false
	};
	
	constructor(){
		this.initDatas  = this.initDatas.bind(this);
		this.setUpdate  = this.setUpdate.bind(this);
		this.setSearchValue  = this.setSearchValue.bind(this);
		this.changeTab  = this.changeTab.bind(this);
		this.setMulitcol  = this.setMulitcol.bind(this);
		this.setIsAbc  = this.setIsAbc.bind(this);
		this.setAbcSelected  = this.setAbcSelected.bind(this);
		this.setShowBeagenters  = this.setShowBeagenters.bind(this);
		this.doAddWfToColl  = this.doAddWfToColl.bind(this);
		this.getImportData  = this.getImportData.bind(this);
		this.setShowImportWf  = this.setShowImportWf.bind(this);
		this.setImportSearchValue  = this.setImportSearchValue.bind(this);
		this.setImportDataShow  = this.setImportDataShow.bind(this);
		this.importWf  = this.importWf.bind(this);
		this.saveLastSet  = this.saveLastSet.bind(this);
	}
	
	//初始化
	@action
	initDatas(params={}){
		this.initParams = params;
		this.title = getLabel(84759,"新建流程");
		if(this.initParams.tabTitle){
			this.title = Base64.decode(decodeURIComponent(this.initParams.tabTitle));
		}
		this.loading = true;
		params.tabkey = this.tabkey;
		API_ADD.doWfInfoGet(params).then((data)=>{
			const {datas,user,createwflabels,tabs = [],userOperateHabit = {},unSupportSPAWf,tips = {}} = data;
			const {hasStruct} = params;
			if(hasStruct == "true") {
				tabs.push({title:getLabel(386167,'流程结构图'),key:"99"});
			}
			const {defaultSelectedTab = '',mulitcol = '',isAbc = ''} = userOperateHabit;
			this.tabkey = defaultSelectedTab == '' ? (ls.getStr('wf-add-tabkey')||'1') : defaultSelectedTab;
			this.mulitcol = mulitcol == '' ? (ls.getStr('wf-add-mulitcol') == 'false' ? false : true) : mulitcol == '1';
			this.isAbc = isAbc == '' ? (ls.getStr('wf-add-isAbc') == 'true') : isAbc == '1';
			this.loading = false;
			this.wftypes = datas;
			this.createwflabels = createwflabels;
      this.tabDatas  = tabs;
			this.showDatas = {...this.showDatas,user:user};
			this.unSupportSPAWf = unSupportSPAWf;
			this.wfTypeTips = tips;
      this.setUpdate(); 
      this.jumpTab(params);
		});
	}
	
	//搜索
	setSearchValue(v){
		this.value  = v;
		this.setUpdate();
	}
	
	//tab切换key
	changeTab(v){
		this.tabkey = v;
		this.abcSelected = '';
		this.setUpdate();
        this.saveLastSet();
  }

  jumpTab = (queryParams = {}) => {
    if(!queryParams.jumpTab) return
    let tabitem = this.tabDatas.filter( v =>  v.key == parseInt(queryParams.jumpTab));
    if(tabitem.length > 0 ) { //如果有常用的流程和我的收藏
      this.changeTab(tabitem[0].key);
    } else {
      this.changeTab('1'); //跳转至全部
    }
 }
	
	//切换列数
	setMulitcol(bool){
		this.mulitcol  = bool;
		this.setUpdate();
        this.saveLastSet();
	}
	
	//是否abc
	setIsAbc(bool){
		this.isAbc = bool;
		this.setUpdate();
        this.saveLastSet();
	}
	
	//设置选中按钮
 	setAbcSelected(v){
 		this.abcSelected = v;
 		this.setUpdate();
 	}
 	
 	//设置展示代理身份创建区域
 	setShowBeagenters(wfid,status){
 		this.wfOperateInfo = {...this.wfOperateInfo,curOperWfid:wfid,showBeagenters:status};
 	}
 	
 	//设置展示流程导入区域
 	setShowImportWf(wfid, status){
		this.wfOperateInfo = {...this.wfOperateInfo,curOperWfid:wfid,showImportWf:status,isDisableImportWfMenu:false};
		if(!status){
			this.importData = [];
			this.importValue = '';
		}
 	}
 	
 	//收藏
 	doAddWfToColl(wfbean,colected){
 		const {id,typeId} = wfbean;
		const wftypes = this.wftypes;
		API_ADD.doAddWfToColl({'workflowid':id,"worktypeid":typeId,"needall":colected}).then(datas=>{
			message.info(colected == '0' ? getLabel(386357,'取消收藏成功') : getLabel(386356,'加入收藏成功'));
		})
		this.wftypes.map(t=>{
			if(t.id == typeId){
				t.wfbeans.map(w=>{
					if(w.id == id){
						w.wfColl = colected;
						t.wftypeColl = colected;
					}
				})
			}
		});
		this.setUpdate();
	}
 	
 	//获取流程导入数据
 	getImportData(params){
 		API_ADD.getRequestImportData(params).then(datas=>{
 			this.importData = datas;
			this.setImportDataShow();
			this.setShowImportWf(params.workflowid, true);
		})
 	}
	
	//搜索导入流程
	setImportSearchValue(v){
		this.importValue = v;
		this.setImportDataShow();
	}
 	
 	setImportDataShow(){
 		const {importData = [],importValue =''} = this;
 		let importDataShow = importData.slice();
		if(importValue){
			importDataShow = importDataShow.filter(i=>{return i.value.indexOf(importValue) >= 0});
		}
		this.importDataShow = importDataShow;
 	}
 	
 	importWf(impobj,wfid){
        this.wfOperateInfo = {...this.wfOperateInfo,isDisableImportWfMenu:true};
 		const params  =  {
			src:"import",
			imprequestid:impobj.data,
			workflowid:wfid,
			formid:impobj.formid,
			isbill:impobj.isbill,
			nodeid:impobj.nodeid,
			nodetype:impobj.nodetype
		};
	
		API_ADD.importWf(params).then(data=>{
			var width = screen.availWidth-10 ;
			var height = screen.availHeight-50 ;
			var szFeatures = "top=0," ;
			szFeatures +="left=0," ;
			szFeatures +="width="+width+"," ;
			szFeatures +="height="+height+"," ;
			szFeatures +="directories=no," ;
			szFeatures +="status=yes,toolbar=no,location=no," ;
			szFeatures +="menubar=no," ;
			szFeatures +="scrollbars=yes," ;
			szFeatures +="resizable=yes" ; //channelmode
			let url  = "/workflow/request/ViewRequestForwardSPA.jsp?requestid="+data.requestid;
			window.open(url,"",szFeatures) ;
		});
 	}
 	
 	
 		//刷新数据
	setUpdate(){
		const showDatas = {};
 	
		//setTypesShow
		const {wftypes,isAbc,tabkey,abcSelected,value = ''} = this;
		const _value = value.toUpperCase();
		
		let typesShow = [];
		let abcBtns = [];
		wftypes.map(w=>{
			let wNew = objectAssign({},w);
			if(_value !== "") {
				wNew.wfbeans = wNew.wfbeans.filter(b=>{return (b.name.toUpperCase().indexOf(_value)>=0 || b.id.indexOf(_value)>=0 || b.spell.indexOf(_value)>=0) });
			}
			if(tabkey == '2') {
				wNew.wfbeans = wNew.wfbeans.filter(b=>{return b.wfColl == "1"});
			}
			typesShow.push(wNew);
		})
		if(isAbc){
    		let typesABC = [];
    		const colorarray = ["#55D2D4","#B37BFA","#FFC62E","#8DCE36","#37B2FF","#FF9537","#FF5E56"];
			for(let i=0; i<27; i++){
        		let wfBeansAbc = [];
        		typesABC.push({
        			"letter": i == 26 ? "···" : String.fromCharCode(65+i),
        			"wfbeans":function(){
	        			typesShow.map(t=>{
    						t.wfbeans.map(b=>{
								b.letter.charCodeAt(0) - 65 == i && i != 26 && wfBeansAbc.push(b);
								i == 26 && (b.letter.charCodeAt(0) >= 91 || b.letter.charCodeAt(0) < 65) && wfBeansAbc.push(b);
        					});
        				});
        				return wfBeansAbc;
        			}(),
        			"color": colorarray[i%7],
        			"disabled": wfBeansAbc.length <= 0,
        			"selected": abcSelected == (i == 26 ? "···" : String.fromCharCode(65+i))
        		});
			}
			abcBtns = typesABC;
			typesShow = typesABC;
		}
		typesShow = typesShow.filter(s=>{
			const {wfbeans =[]} = s;
			return wfbeans.length > 0;
		});
		showDatas.typesShow = typesShow;
		showDatas.abcBtns = abcBtns;
	
		//setTypesCols
		const docWidth = document.documentElement.clientWidth;
		let typesCols = docWidth > 1400 ? [[],[],[],[]] : (docWidth > 1100 ? [[],[],[]] : (docWidth > 600 ? [[],[]] : [[]]));
		let colHeight = docWidth > 1400 ? [0,0,0,0] : (docWidth > 1100 ? [0,0,0] : (docWidth > 600 ? [0,0] : [0]));
		typesShow.length > 0 && typesShow.map(t=>{
			const {wfbeans = []} = t;
			if(wfbeans.length >= 0){
				let minH = Math.min.apply(Math, colHeight);
	   			for(let i = 0 ;i < colHeight.length;i++){
	   				if(colHeight[i] == minH){
	   					typesCols[i].push(t);
	   					colHeight[i] += wfbeans.length + 3;
	   					break;
	   				}
	   			}
			}
		});
		showDatas.typesCols  = typesCols;
	
		//setUsedBeans
		let usedBeans = [];
		typesShow.length > 0 && typesShow.map(t=>{
			const {wfbeans =[]} = t;
			wfbeans.map(b=>{
				b && b.usedtodo == '1' && usedBeans.push(b)
			});
		})
		usedBeans.sort((a,b)=>{
			return a.usedtodoorder - b.usedtodoorder;
		})
		showDatas.usedBeans = usedBeans;
		this.showDatas = {...this.showDatas,...showDatas};
 	}

    saveLastSet(){
		const params = {'wfDefaultSelectedTabKey':this.tabkey,'mulitcol': this.mulitcol ? '1' :'0','isAbc':this.isAbc ? '1':'0'};
		API_ADD.saveUserOperateHabit(params);
	}
}